package com.dingup.provider.service.student.impl;

import com.dingup.api.Util.PasswordUtil;
import com.dingup.api.adapter.student.StudentCourseInformationAdapter;
import com.dingup.api.bean.page.PageData;
import com.dingup.api.bean.requestBean.student.StudentPageBean;
import com.dingup.api.enums.StudentCampusEnum;
import com.dingup.api.model.student.Student;
import com.dingup.api.model.student.StudentBind;
import com.dingup.api.model.sys.SysDept;
import com.dingup.api.model.sys.SysUser;
import com.dingup.api.model.sys.SysUserDept;
import com.dingup.api.model.sys.SysWxUser;
import com.dingup.provider.mapper.SysDeptMapper;
import com.dingup.provider.mapper.SysUserDeptMapper;
import com.dingup.provider.mapper.SysUserMapper;
import com.dingup.provider.mapper.SysWxUserMapper;
import com.dingup.provider.service.student.StudentCourseService;
import com.dingup.provider.service.sys.SysUserService;
import com.dingup.provider.service.student.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2018/8/2.
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysDeptMapper sysDeptMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserDeptMapper sysUserDeptMapper;
    @Autowired
    SysWxUserMapper sysWxUserMapper;
    @Autowired
    StudentCourseService studentCourseService;



    @Override
    public String save(SysUser user, List<Integer> roleIds) {
        Long[] deptIds = null;
        return sysUserService.save(user,deptIds, roleIds);
    }

    @Override
    public List<SysDept> getDeptByUserId(String userId) {

        List<SysDept> depts = sysDeptMapper.getDeptByUserId(userId);
        List<SysDept> res = new ArrayList<>();
        depts.stream().forEach(
                d -> {
                    SysDept sysDept = new SysDept();
                    sysDept.setId(d.getId());
                    sysDept.setName(d.getName());
                    sysDept.setParentId(d.getParentId());
                    res.add(sysDept);
                }
        );
        return res;
    }

    @Override
    @Transactional
    public Boolean updateStudent(SysUser student, Long[] deptIds) {
        sysUserMapper.updateByPrimaryKeySelective(student);
        if (deptIds!=null){
            sysUserDeptMapper.deleteByUserId(student.getUserId());
            Arrays.stream(deptIds).forEach(
                    d -> {
                        SysUserDept sysUserDept = new SysUserDept();
                        sysUserDept.setIfDelete(false);
                        sysUserDept.setStatus(false);
                        sysUserDept.setSysDeptId(d);
                        sysUserDept.setSysUserId(student.getUserId());
                        sysUserDeptMapper.insertSelective(sysUserDept);
                    }
            );
        }
        return true;
    }

    @Override
    public Boolean freezeStudent(String studentId) {
        return sysUserService.delete(studentId);
    }

    @Override
    @Transactional
    public Boolean activeStudent(String studentId, String password) {
        if (!StringUtils.isEmpty(password)) {
            SysUser user = sysUserMapper.selectByPrimaryKey(studentId);
            if (user.getIfActive()){
                //学生已经激活 无需再次激活
                return false;
            }
            SysUser student = new SysUser();
            student.setUserId(studentId);
            student.setIfActive(true);
            student.setUserPassword(PasswordUtil.encoder(password));
            sysUserMapper.updateByPrimaryKeySelective(student);
        }
        sysUserService.active(studentId);
        return true;
    }

    @Override
    public PageData<Student> getStudent(Student student, List<String> userIds) {
        student.setCreateUserIds(userIds);
        List<Student> students = sysUserMapper.selectStudent(student);
        ifHasUnFinishLessonMsg(students);
        Integer total = sysUserMapper.selectStudentTotal(student);
        PageData<Student> pageInfo = new PageData<>();
        pageInfo.setData(students);
        pageInfo.setTotal(total);
        pageInfo.setPage(student.getPage());
        pageInfo.setRows(student.getRows());
        return pageInfo;
    }

    @Override
    public Student getStudentById(String studentId) {
        SysUser user = sysUserMapper.selectByPrimaryKey(studentId);
        if (user != null) {
            String[] zone = user.getMobile().split("-");
            StudentBind student = new StudentBind();
            if (zone.length > 1) {
                student.setMobile(zone[1]);
                student.setZoneNum(zone[0]);
            }
            List<StudentCourseInformationAdapter> course = studentCourseService.getStudentCourseByStudentId(user.getUserId());
            if (!CollectionUtils.isEmpty(course)){
                Set<String> campusIds = course.stream().map(s->s.getLessonCampus()).filter(s->s!=null).collect(Collectors.toSet());
                if (!CollectionUtils.isEmpty(campusIds)){
                    List<Map<String,Object>> campus = campusIds.stream().map(c->StudentCampusEnum.getMap(c)).collect(Collectors.toList());
                    student.setDepts(campus);
                }
            }
            student.setEmail(user.getEmail());
            student.setIfActive(user.getIfActive());
            student.setStudentAccount(user.getUserAccount());
            student.setStudentName(user.getUserName());
            if (user.getIfActive()){
                student.setIfUpdatePassword(true);
            }
            SysWxUser oneself = sysWxUserMapper.getWxForOneselfByUserId(studentId);
            if (oneself != null) {
                student.setIfBindForOneself(true);
                student.setWechatName(oneself.getNickName());
                student.setHeadUrl(oneself.getAvatarUrl());
            }
            SysWxUser forReport = sysWxUserMapper.getWxForReportByUserId(studentId);
            if (forReport != null) {
                student.setIfBindForReport(true);
                student.setWechatForStudyReport(forReport.getNickName());
            }
            return student;
        }

        return null;
    }

    @Override
    public PageData<Student> getStudentByStudentPageBean(StudentPageBean studentPageBean, List<String> userIds) {
        studentPageBean.setCreateUserIds(userIds);
        List<Student> students = sysUserMapper.selectStudentByPageBean(studentPageBean);
        ifHasUnFinishLessonMsg(students);
        Integer total = sysUserMapper.selectStudentTotalByPageBean(studentPageBean);
        PageData<Student> pageInfo = new PageData<>();
        pageInfo.setData(students);
        pageInfo.setTotal(total);
        pageInfo.setPage(studentPageBean.getPage());
        pageInfo.setRows(studentPageBean.getRows());
        return pageInfo;
    }

    private void ifHasUnFinishLessonMsg(List<Student> students){
        students.stream().forEach(
                student -> {
                    student.setIfHasUnFinishLessonMsg(studentCourseService.ifHasUnFinishLessonMsg(student));
                    student.setIfHasNullClassMsg(studentCourseService.ifHasNullClassMsg(student));
                }
        );
    }

}
